package com.qujia.system.domain.vo;


import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import java.io.*;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.util.Arrays;
import java.util.Map;

/**
 * com.mfhcd.biz.gateway.utils
 *
 * @author guotl
 * @date 2020-2020/5/20:18:00
 * @Description: cfca证书工具类
 */

public class CfcaCertUtil {

/**
     * 对消息进行签名
     *
     * @param srcMessage 原始消息
     * @param pfxPath    证书路径
     * @param password   获取密钥的密码
     * @return b64SignMsg 签名数据
     */
    public static byte[] signMessage(String srcMessage, String pfxPath, String password) throws Exception{
        byte[] b64SignMsg = null;
        try {
            Signature signature = Signature.getInstance("SHA256withRSA");
            //获取私匙
            PrivateKey privateKey = RSAKeyUtil.getPrivateKey(pfxPath, "pfx", password);
            signature.initSign(privateKey);
            signature.update(srcMessage.getBytes());
            b64SignMsg = Base64.encodeBase64(signature.sign());
        } catch (Exception e) {
            throw new Exception("调用CFCA证书签名异常"+e.getMessage());
        }
        return b64SignMsg;
    }

/**
     * 对消息进行验签
     * MD5withRSAEncryption
     * @param srcMessage 原始消息
     * @param signData   签名数据
     * @param bCert      公钥编码
     * @return true表示验签成功；false表示验签失败
     */
    public static boolean verifyMessage(String srcMessage, String signData, byte[] bCert) throws Exception {
        boolean verifyFlag = false;
        try {
            PublicKey publicKey = RSAKeyUtil.getPublicKey(bCert);
            Signature verifyCheck = Signature.getInstance("SHA256withRSA");
            verifyCheck.initVerify(publicKey);
            verifyCheck.update(srcMessage.getBytes("UTF-8"));
            verifyFlag = verifyCheck.verify(Base64.decodeBase64(signData));
        } catch (Exception e) {
            throw new Exception("CFCA证书验签异常");
        }
        return verifyFlag;
    }

    /**
     * 验签url解析封装
     * @param srcMessage
     * @param signValue
     * @param CER_PATH
     * @return
     */
    public static boolean verifyValue(String srcMessage, String signValue, String CER_PATH) throws Exception{
        StringBuffer buffer = new StringBuffer();
        try {
            File file = new File(CER_PATH);
            FileReader reader = new FileReader(file);
            BufferedReader bufferedReader = new BufferedReader(reader);
            String line = null;
            while ((line = bufferedReader.readLine()) != null) {
                buffer.append(line);
            }
            reader.close();
        } catch (Exception e) {
            throw new Exception("CFCA证书读取公钥异常");
        }
        String cerStr = buffer.toString().replace("-----BEGIN CERTIFICATE-----", "").replace("-----END CERTIFICATE-----", "");
        return verifyMessage(srcMessage, signValue, Base64Util.decode(cerStr));
    }

    /**
     * 文件流方法
     * @param srcMessage
     * @param signValue
     * @param is
     * @return
     */
    public static boolean verifyValue(String srcMessage, String signValue, InputStream is) throws Exception{
        StringBuffer buffer = new StringBuffer();
        try {
//            File file = new File(CER_PATH);
//            FileReader reader = new FileReader(file);
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is));
            String line = null;
            while ((line = bufferedReader.readLine()) != null) {
                buffer.append(line);
            }
            bufferedReader.close();
        } catch (Exception e) {
            throw new Exception("CFCA证书读取公钥异常");
        }
        String cerStr = buffer.toString().replace("-----BEGIN CERTIFICATE-----", "").replace("-----END CERTIFICATE-----", "");
        return verifyMessage(srcMessage, signValue, Base64Util.decode(cerStr));
    }


    public static String getPlaintext(Map<String, ?> params) {
        Object[] array = params.keySet().toArray();
        Arrays.sort(array);
        StringBuffer sb = new StringBuffer();
        //需要排除的字段
        String[] exField = {"signValue", "token"};

        for (int i = 0; i < array.length; i++) {
            if (null != params.get(array[i])
                    && params.get(array[i]) != null
                    && !"".equals(params.get(array[i]).toString().trim())
                    && Arrays.binarySearch(exField, array[i]) < 0) {
                sb.append(array[i]);
                sb.append("=");
                sb.append(params.get(array[i]));
                sb.append("&");
            }
        }
        String signData = sb.toString();
        if (signData.endsWith("&")) {
            signData = signData.substring(0, signData.length() - 1);
        }
        return signData;
    }


    /**
     * 读取公钥证书--文件路径方法
     * @param publicCertPath
     * @return
     * @throws Exception
     */
    public static String getCertPublicKey(String publicCertPath)throws Exception{
        StringBuffer buffer = new StringBuffer();
        try {
            File file = new File(publicCertPath);
            FileReader reader = new FileReader(file);
            BufferedReader bufferedReader = new BufferedReader(reader);
            String line = null;
            while ((line = bufferedReader.readLine()) != null) {
                buffer.append(line);
            }
            reader.close();
        } catch (Exception e) {
            throw new Exception("CFCA证书读取公钥异常",e);
        }
        String cerStr = buffer.toString().replace("-----BEGIN CERTIFICATE-----", "").replace("-----END CERTIFICATE-----", "");
        return cerStr;
    }


    /**
     * 读取公钥证书--文件流方法
     * @param is
     * @return
     * @throws Exception
     */
    public static String getCertPublicKey(InputStream is)throws Exception{
        StringBuffer buffer = new StringBuffer();
        try {
//            File file = new File(publicCertPath);
//            FileReader reader = new FileReader(file);
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is));
            String line = null;
            while ((line = bufferedReader.readLine()) != null) {
                buffer.append(line);
            }
            bufferedReader.close();
        } catch (Exception e) {
            throw new Exception("CFCA证书读取公钥异常",e);
        }
        String cerStr = buffer.toString().replace("-----BEGIN CERTIFICATE-----", "").replace("-----END CERTIFICATE-----", "");
        return cerStr;
    }


    // MAX_DECRYPT_BLOCK应等于密钥长度/8（1byte=8bit），所以当密钥位数为2048时，最大解密长度应为256.
    // 128 对应 1024，256对应2048
    private static final int KEYSIZE = 2048;

    // RSA最大加密明文大小
    private static final int MAX_ENCRYPT_BLOCK = 117;

    // RSA最大解密密文大小
    	//private static final int MAX_DECRYPT_BLOCK = 256;

    private static final int MAX_DECRYPT_BLOCK = KEYSIZE / 8;



    /**
     * 解密
     *
     * @param msg 报文密文
     */
    public static String decrypt(String msg, String pfxPath,String password) {
        try {

            //得到私钥对象
            PrivateKey privateKey = RSAKeyUtil.getPrivateKey(pfxPath, "pfx", password);

            Cipher cipher = Cipher.getInstance("RSA");
            //传递私钥，设置为解密模式。
            cipher.init(Cipher.DECRYPT_MODE, privateKey);
            //得到报文密文的长度

            byte[] byte_bwmw = Base64.decodeBase64(msg);

            int inputLen = byte_bwmw.length;

            ByteArrayOutputStream out = new ByteArrayOutputStream();
            int offSet = 0;
            byte[] cache;
            int i = 0;
            // 对数据分段解密
            while (inputLen - offSet > 0) {
                if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
                    cache = cipher.doFinal(byte_bwmw, offSet, MAX_DECRYPT_BLOCK);
                } else {
                    cache = cipher.doFinal(byte_bwmw, offSet, inputLen - offSet);
                }
                out.write(cache, 0, cache.length);
                i++;
                offSet = i * MAX_DECRYPT_BLOCK;
            }
            //解密后的数据
            byte[] data = out.toByteArray();
            out.close();
            return new String(data);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("解密异常......");
            return null;
        }
    }

    /**
     * 加密--文件路径方法
     *
     * @param src 明文
     * @return
     */
    public static String encrypt(String src, String publicCertPath) {

        byte[] encryptedDatas = new byte[0];
        try {

            String publicKeyStr = getCertPublicKey(publicCertPath);
            PublicKey publicKey = RSAKeyUtil.getPublicKey(Base64Util.decode(publicKeyStr));

            //得到Cipher对象来实现对源数据的RSA加密
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);

            byte[] encryptedData = src.getBytes();
            int inputLen = encryptedData.length;
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            int offSet = 0;
            byte[] cache;
            int i = 0;
            // 对数据分段加密  doFinal
            while (inputLen - offSet > 0) {
                if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
                    cache = cipher.doFinal(encryptedData, offSet, MAX_ENCRYPT_BLOCK);
                } else {
                    cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);
                }
                out.write(cache, 0, cache.length);
                i++;
                offSet = i * MAX_ENCRYPT_BLOCK;
            }
            encryptedDatas = out.toByteArray();
            //获取到报文的长度
            int length = encryptedDatas.length;
            System.out.println("报文长度是：" + length);

            out.close();
        } catch (Exception e) {
            System.out.println("加密异常...");
            e.printStackTrace();
        }
        return Base64.encodeBase64String(encryptedDatas);
    }


    /**
     * 加密--文件流方法
     *
     * @param src 明文
     * @return
     */
    public static String encrypt(String src, InputStream is) {

        byte[] encryptedDatas = new byte[0];
        try {

            String publicKeyStr = getCertPublicKey(is);
            PublicKey publicKey = RSAKeyUtil.getPublicKey(Base64Util.decode(publicKeyStr));

            //得到Cipher对象来实现对源数据的RSA加密
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);

            byte[] encryptedData = src.getBytes();
            int inputLen = encryptedData.length;
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            int offSet = 0;
            byte[] cache;
            int i = 0;
            // 对数据分段加密  doFinal
            while (inputLen - offSet > 0) {
                if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
                    cache = cipher.doFinal(encryptedData, offSet, MAX_ENCRYPT_BLOCK);
                } else {
                    cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);
                }
                out.write(cache, 0, cache.length);
                i++;
                offSet = i * MAX_ENCRYPT_BLOCK;
            }
            encryptedDatas = out.toByteArray();
            //获取到报文的长度
            int length = encryptedDatas.length;
            System.out.println("报文长度是：" + length);

            out.close();
        } catch (Exception e) {
            System.out.println("加密异常...");
            e.printStackTrace();
        }
        return Base64.encodeBase64String(encryptedDatas);
    }


}

